import { JSEncrypt } from 'jsencrypt'
import { utils, writeFile } from 'xlsx'
import moment from 'moment'
import axios from 'axios'
import { getToken } from './auth'

// 将一级结构数据转换为级联关系数据
export function DealData<T = any> (
  d: T[], // 目标数据
  dataWork?: (item: T) => void | null, // 处理数据函数
  parentKey: string = 'pid', // 匹配父节点字段key
  currentKey: string = 'id' // 匹配当前节点key
) {
  const instanse = JSON.parse(JSON.stringify(d))
  const map = {}
  for (let i = 0; i < instanse.length; i++) {
    delete instanse[i].children
    if (instanse[i][currentKey]) {
      map[instanse[i][currentKey]] = instanse[i]
    }
  }
  const treeData = []
  for (let i = 0; i < instanse.length; i++) {
    const child = instanse[i]
    dataWork && dataWork(child)
    const mapItem = map[child[parentKey]]
    if (mapItem) {
      (mapItem.children || (mapItem.children = [])).push(child)
    } else {
      treeData.push(child)
    }
  }
  return treeData
}

/*
  解决级联选择反向关联
  @param [array] data = T[] --数据源没有层级关系
  @param [number | string] id 目标id
  @param [boolean] isChildren = true 是否包含自身节点，用来处理编辑跟新增的差异
*/
export function RevertTreeToArray<T> (data: any[], id: number | string, isChildren: boolean = true) {
  const result: T[] = []
  const filterData = (pid: number | string) => {
    data.forEach((item: any) => {
      if (item.id === pid) {
        if (item.pid) {
          filterData(item.pid)
        }
        result.push(item.id)
      }
    })
  }
  filterData(id)
  if (!isChildren) result.pop()
  return result
}

// rsa公钥加密
export function getEncrypt (val: string) {
  const encrypt = new JSEncrypt()
  encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPr06t2imH3wd8ZmjemU2TBH7iqbYtCgI6WIm0A5anMItIsnEL2XZo-U8GbfCiHLx5IGPDyO9jfvbXRT3WRuDWG6l8VAXECuhEw-4HtEVsyPObhq--QUih_A1fEDbIbnFWE1-c_FwBde8eljwLNWxkZjGM1MElm8ZAPxXF8y8njwIDAQAB')
  return encrypt.encrypt(val)
}

// 权限判断
export function checkPermission (biulid: string[]) {
  console.log(biulid)
  return true
}

// 导出excel
export function exportData (h: any[], b: any[], n: string = moment().format('YYYY-MM-DD_HH:mm:ss')) {
  const data: any[] = []
  b.forEach(row => {
    const obj = {}
    h.forEach(item => {
      let val = row[item.prop] || ''
      if (item.formatter) {
        val = item.formatter(row, item)
      }
      obj[item.label] = val
    })
    data.push(obj)
  })
  const wb = utils.book_new()
  const ws = utils.json_to_sheet(data)
  utils.book_append_sheet(wb, ws)
  writeFile(wb, `${n}.xlsx`, {
    bookType: 'xlsx'
  })
}

// 从身份证号读取年龄
export function getOldByIdcard (idcard: string | any[]) {
  if (idcard && idcard.length === 18) {
    const gds = Number(idcard.slice(6, 10))
    const old = new Date().getFullYear() - gds
    return old
  }
  return '(空)'
}

export function downloadFile (url: string) {
  axios({
    headers: {
      token: getToken('userToken'),
      appToken: getToken('appToken'),
      cookie: document.cookie
    },
    method: 'get',
    url,
    responseType: 'blob'
  }).then((res) => {
    const link = document.createElement('a')
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    // 获取heads中的filename文件名
    const aa = res.headers['content-disposition']
    const temp = aa.split(';')[1].split('filename=')[1]
    const fileName = decodeURIComponent(temp).replaceAll('"', '')
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', fileName)
    link.click()
  }).catch(error => {
    console.log(error)
  })
}

/**
 * 日期格式化
 * @param {*} date
 * @param {*} fmt
 */
export function dateFormat (date: any, fmt: string) {
  if (date === 'Invalid Date') return ''
  date = new Date(date)
  const a = ['日', '一', '二', '三', '四', '五', '六']
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
    w: date.getDay(), // 周
    W: a[date.getDay()], // 大写周
    T: 'T'
  }
  if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k as keyof typeof o]) : (('00' + o[k as keyof typeof o]).substr(('' + o[k as keyof typeof o]).length))) }
  }
  return fmt
}

// 深拷贝
const isArr = (origin: any): boolean => {
  const str = '[object Array]'
  return Object.prototype.toString.call(origin) === str
}

export function deepClone <T> (origin: T, target?: Record<string, any> | T): T {
  const tar = target || {}
  for (const key in origin) {
    if (Object.prototype.hasOwnProperty.call(origin, key)) {
      if (typeof origin[key] === 'object' && origin[key] !== null) {
        tar[key] = isArr(origin[key]) ? [] : {}
        deepClone(origin[key], tar[key])
      } else {
        tar[key] = origin[key]
      }
    }
  }
  return tar as T
}
